package com.fantasyland.backend.controller;

import com.fantasyland.backend.Entity.Reply;
import com.fantasyland.backend.Service.ReplyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/posts")
@CrossOrigin(
    origins = {"http://localhost:5173", "http://127.0.0.1:5173"}, 
    methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS},
    allowedHeaders = "*",
    allowCredentials = "true"
)
public class ReplyController {

    private static final Logger logger = LoggerFactory.getLogger(ReplyController.class);

    @Autowired
    private ReplyService replyService;

    /**
     * 获取帖子的所有回复
     */
    @GetMapping("/{postId}/replies")
    public ResponseEntity<List<Reply>> getReplies(@PathVariable Long postId) {
        try {
            List<Reply> replies = replyService.getRepliesByPostId(postId);
            return ResponseEntity.ok(replies);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 添加新回复
     */
    @PostMapping("/{postId}/replies")
    public ResponseEntity<?> addReply(
            @PathVariable Long postId,
            @RequestBody Map<String, String> request) {
        try {
            logger.info("收到添加回复请求 - postId: {}, request: {}", postId, request);
            
            String content = request.get("content");
            String author = request.get("author");
            
            logger.debug("解析请求参数 - content: {}, author: {}", content, author);
            
            if (content == null || content.trim().isEmpty()) {
                logger.warn("回复内容为空");
                Map<String, String> error = new HashMap<>();
                error.put("error", "回复内容不能为空");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (author == null || author.trim().isEmpty()) {
                logger.warn("作者名称为空");
                Map<String, String> error = new HashMap<>();
                error.put("error", "作者名称不能为空");
                return ResponseEntity.badRequest().body(error);
            }
            
            logger.info("开始添加回复 - postId: {}, content: {}, author: {}", 
                       postId, content.trim(), author.trim());
            
            Reply newReply = replyService.addReply(postId, content.trim(), author.trim());
            
            logger.info("成功添加回复 - replyId: {}", newReply.getId());
            return ResponseEntity.ok(newReply);
            
        } catch (Exception e) {
            logger.error("添加回复失败 - postId: {}, error: {}", postId, e.getMessage(), e);
            
            Map<String, String> error = new HashMap<>();
            error.put("error", "添加回复失败: " + e.getMessage());
            error.put("postId", postId.toString());
            
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 获取帖子回复数量
     */
    @GetMapping("/{postId}/replies/count")
    public ResponseEntity<Map<String, Integer>> getReplyCount(@PathVariable Long postId) {
        try {
            int count = replyService.getReplyCount(postId);
            return ResponseEntity.ok(Map.of("count", count));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 删除帖子的所有回复
     */
    @DeleteMapping("/{postId}/replies")
    public ResponseEntity<Void> deleteReplies(@PathVariable Long postId) {
        try {
            replyService.deleteRepliesByPostId(postId);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
}